package leetcode.median;

import leetcode.base.ListNode;

public class $61_RotateRight {
    public ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null || head.next == null) {
            return head;
        }

        ListNode tail = head;
        int len = 0;
        while (tail != null) {
            tail = tail.next;
            len++;
        }
        int rotate = k % len;
        if (rotate == 0) {
            return head;
        }

        ListNode fast = head;
        ListNode slow = head;
        while (rotate > 0) {
            fast = fast.next;
            rotate--;
        }

        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        ListNode newHead = slow.next;
        slow.next = null;
        fast.next = head;
        return newHead;
    }
}
